package com.sky.service.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.vo.*;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;

/**
 * 统计业务
 */
@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = CollUtil.newArrayList();
        List<Double> turnoverList = CollUtil.newArrayList();

        //遍历日期
        while (!(begin.isAfter(end))){
            LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(begin, LocalTime.MAX);
            //查每天营业额
            Double turnover = orderMapper.sumTurnoverByDate(beginTime,endTime);
            if (ObjectUtil.isNull(turnover)){
                turnover = 0.0;
            }
            turnoverList.add(turnover);
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        //集合转成字符串
        String dateStr = dateList.stream().map(date ->{
           return (DateTimeFormatter.ofPattern("yyyy-MM-dd")).format(date);
        }).collect(Collectors.joining(","));

        String turnoverStr = turnoverList.stream().map(Object::toString
        ).collect(Collectors.joining(","));

        return TurnoverReportVO.builder().turnoverList(turnoverStr).dateList(dateStr).build();
    }


    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = CollUtil.newArrayList();
        List<Integer> newUserList = CollUtil.newArrayList();
        List<Integer> totalUserList = CollUtil.newArrayList();

        //遍历日期
        while (!(begin.isAfter(end))){
            LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(begin, LocalTime.MAX);
            //查总用户数
            Map<String, Object> map = MapUtil.newHashMap();
            map.put("endTime",endTime);
            Integer countNewUser = userMapper.countUserByMap(map);
            totalUserList.add(countNewUser);

            //查当日新增用户数
            map.put("beginTime",beginTime);
            countNewUser = userMapper.countUserByMap(map);
            newUserList.add(countNewUser);
            dateList.add(begin);
            begin = begin.plusDays(1);
        }

        //集合转字符串
        String dateStr = dateList.stream().map(date -> {
            return date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        }).collect(Collectors.joining(","));

        String newUserStr = newUserList.stream().map(Object::toString).collect(Collectors.joining(","));

        String totalUserStr = totalUserList.stream().map(Object::toString).collect(Collectors.joining(","));

        return UserReportVO.builder().dateList(dateStr).newUserList(newUserStr).totalUserList(totalUserStr).build();
    }


    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = CollUtil.newArrayList();
        List<Integer> orderCountList = CollUtil.newArrayList();
        List<Integer> validOrderCountList = CollUtil.newArrayList();

        //遍历日期
        while (!(begin.isAfter(end))){
            LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(begin, LocalTime.MAX);
            //每日订单数
            Map<String, Object> map = MapUtil.newHashMap();
            map.put("beginTime",beginTime);
            map.put("endTime",endTime);
            Integer orderCount = orderMapper.orderCountListByMap(map);
            orderCountList.add(orderCount);

            //每日有效订单数
            map.put("status", Orders.COMPLETED);
            Integer validOrderCount = orderMapper.orderCountListByMap(map);
            validOrderCountList.add(validOrderCount);

            //日期
            dateList.add(begin);
            begin = begin.plusDays(1);
        }

        //订单总数
        Integer totalOrder = orderCountList.stream().reduce(new BinaryOperator<Integer>() {
            @Override
            public Integer apply(Integer integer, Integer integer2) {
                return integer + integer2;
            }
        }).orElse(0);

        //有效订单数
        Integer completeCount = validOrderCountList.stream().reduce(new BinaryOperator<Integer>() {
            @Override
            public Integer apply(Integer integer, Integer integer2) {
                return integer + integer2;
            }
        }).orElse(0);

        //订单完成率
        double rate = 0D;
        if (totalOrder != 0){
            rate = 1.0 * completeCount / totalOrder;
        }
        //封装OrderReportVO
        return OrderReportVO.builder()
                .dateList(dateList.stream().map(date -> {
            return date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        }).collect(Collectors.joining(",")))
                .orderCompletionRate(rate)
                .orderCountList(orderCountList.stream().map(Object::toString).collect(Collectors.joining(",")))
                .totalOrderCount(totalOrder)
                .validOrderCount(completeCount)
                .validOrderCountList(validOrderCountList.stream().map(Object::toString).collect(Collectors.joining(",")))
                .build();
    }


    /**
     * 统计top10
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO SalesTop10(LocalDate begin, LocalDate end) {
        List<String> nameList = CollUtil.newArrayList();
        List<String> numberList = CollUtil.newArrayList();

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        //销量前10的商品名称和销量
        List<GoodsSalesDTO> goodsSalesDTOS = orderMapper.SalesTop10(beginTime,endTime,Orders.COMPLETED);

        //封装SalesTop10ReportVO
        String nameStr = goodsSalesDTOS.stream().map(goodsSalesDTO -> {
            return goodsSalesDTO.getName();
        }).collect(Collectors.joining(","));

        String numberStr = goodsSalesDTOS.stream().map(goodsSalesDTO -> {
            return goodsSalesDTO.getNumber().toString();
        }).collect(Collectors.joining(","));

        return SalesTop10ReportVO.builder()
                .nameList(nameStr)
                .numberList(numberStr)
                .build();
    }


    /**
     * 导出营业数据报表
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) throws IOException {
        //从类路径下读取excel
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        XSSFWorkbook workbook = new XSSFWorkbook(is);
        XSSFSheet sheet = workbook.getSheetAt(0);
        //准备数据
        LocalDate today = LocalDate.now();
        LocalDate beginDate = today.minusDays(30);
        LocalDate endDate = today.minusDays(1);
        BusinessDataVO businessDataVO = getBusinessData(beginDate, endDate);
        //写入时间
        XSSFRow row = sheet.getRow(1);
        row.getCell(1).setCellValue(beginDate.toString() + "到" + endDate.toString());
        //写入概览数据
        sheet.getRow(3).getCell(2).setCellValue(businessDataVO.getTurnover());
        sheet.getRow(3).getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
        sheet.getRow(3).getCell(6).setCellValue(businessDataVO.getNewUsers());
        sheet.getRow(4).getCell(2).setCellValue(businessDataVO.getValidOrderCount());
        sheet.getRow(4).getCell(4).setCellValue(businessDataVO.getUnitPrice());

        //写入明细数据
        int rowNum = 7;
        while (!(beginDate.isAfter(endDate))){
            BusinessDataVO data = getBusinessData(beginDate, beginDate);
            XSSFRow row2 = sheet.getRow(rowNum);
            row2.getCell(1).setCellValue(beginDate.toString());
            row2.getCell(2).setCellValue(data.getTurnover());
            row2.getCell(3).setCellValue(data.getValidOrderCount());
            row2.getCell(4).setCellValue(data.getOrderCompletionRate());
            row2.getCell(5).setCellValue(data.getUnitPrice());
            row2.getCell(6).setCellValue(data.getNewUsers());
            rowNum++;
            beginDate = beginDate.plusDays(1);
        }
        workbook.write(response.getOutputStream());
    }

    /**
     * 获取营业数据
     * @param beginDate
     * @param endDate
     * @return
     */
    private BusinessDataVO getBusinessData(LocalDate beginDate, LocalDate endDate) {
        BusinessDataVO vo = new BusinessDataVO();
        LocalDateTime beginTime = LocalDateTime.of(beginDate, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(endDate, LocalTime.MAX);
        //营业额
        Double turnover = orderMapper.sumTurnoverByDate(beginTime, endTime);
        if (turnover == null){
            turnover = 0D;
        }
        vo.setTurnover(turnover);
        //订单完成率
            //订单总数
        Map<String, Object> map = MapUtil.newHashMap();
        map.put("beginTime",beginTime);
        map.put("endTime",endTime);
        Integer totalOrders = orderMapper.orderCountListByMap(map);
          //有效订单数
        map.put("status",Orders.COMPLETED);
        Integer validOrderCount = orderMapper.orderCountListByMap(map);
        vo.setValidOrderCount(validOrderCount);
        if (totalOrders == 0){
            Double orderCompletionRate = 0D;
            vo.setOrderCompletionRate(orderCompletionRate);
        }else {
            Double orderCompletionRate = 1.0 * validOrderCount / totalOrders;
            vo.setOrderCompletionRate(orderCompletionRate);
        }
        //新增用户数
        Integer newUsers = userMapper.countUserByMap(map);
        vo.setNewUsers(newUsers);
        //平均客单价
        if (validOrderCount != 0){
            vo.setUnitPrice(turnover / validOrderCount);
        }else {
            vo.setUnitPrice(0D);
        }
        return vo;
    }

}
